Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Repository

'--- Created Date On : 20-Sep-2010 (Gyana)

Public Class frmPatientSearch
    Dim mstrMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim gridView1 As Views.Grid.GridView
    Dim mblnCancelDisplay As Boolean
    Public mstrMenuList(6)() As String    'Keeps menu details (Jagged Arrays)

    Public PatienIdArray() As Integer
    Public PatientIdForAppointment As Integer
    Public PatientNameForAppointment As String
    Private SingleClickOnGridExit As Boolean
    Private SelectMultiPatients As Boolean


    Public Sub New(Optional ByVal IsSingleClickOnGridExit As Boolean = False, Optional ByVal IsSelectMultiPatients As Boolean = False)
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        SingleClickOnGridExit = IsSingleClickOnGridExit
        SelectMultiPatients = IsSelectMultiPatients
    End Sub


    Private Sub frmPatientSearch_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 20
                'Fill Town combo
                Call PopulateLookupDX(lkTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")
                'Call PopulateData()
                pbRecords.Position = 100
                pbRecords.Visible = False
                grdRecords.Focus()
                txtFirstName.Text = "*"
                txtLastName.Text = "*"
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub frmPatientSearch_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            'if both options that is SingleClickOn and SelectMultiPatients are True then it must not be allowed .This warning should be for programmer if he accidently makes both values true.
            If SingleClickOnGridExit AndAlso SelectMultiPatients Then
                MessageBox.Show("SingleClickOn and SelectMultiPatients can not be True at the same time.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.Close()
            End If

            If SelectMultiPatients = True Then
                btnAddPatient.Text = "&OK" 'user will click OK to confirm selection
            End If

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmPatientSearch")
            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False
            If SelectMultiPatients = False Then
                gdvRecords.GroupPanelText = "Click row to select patient."
                gdvRecords.OptionsView.ShowGroupPanel = True
            ElseIf SelectMultiPatients = True Then
                gdvRecords.GroupPanelText = ""
                gdvRecords.OptionsView.ShowGroupPanel = False
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub PopulateData()
        Dim dsRecords As New DataSet   'For populating data in XtraGrid
        Dim strQuery As String

        Try
            If IsValidEntry() = False Then
                Exit Sub
            End If
            pbRecords.Position = 40 : Application.DoEvents()

            strQuery = "SELECT DISTINCT " & IIf(SelectMultiPatients, "CAST(0 AS BIT) AS SelectPatient, ", String.Empty) & _
                        " tblPatientInfo.PatientId as [record_id],PatientTitle + ' ' + (IsNull(LastName + ', ' , '') + FirstName + Isnull(' ' + MiddleName, '') ) as Name, " & _
                        "DATEDIFF(yy,DateOfBirth,GETDATE()) as Age,(IsNull(Address1,'') + case when Address2=Null " & _
                        "or Address2='' then ' ' else ', ' + Address2 End) as Address ,Sex,LastName FROM " & _
                        "tblPatientInfo INNER JOIN LtblSex ON tblPatientInfo.SexId=LtblSex.SexId LEFT OUTER JOIN " & _
                        "tblVisits ON tblPatientInfo.PatientId=tblVisits.PatientId WHERE  Void=0 and IsDecreased=0 and " '& DoctorCriteria

            'Query for search by name
            If rgbSearchBy.SelectedIndex = 0 Then
                
                Dim Fname, LName As String
                'Replace * by % in name textboxes
                Fname = txtFirstName.Text.Replace("*", "%")
                LName = txtLastName.Text.Replace("*", "%")
                'write the string
                strQuery = strQuery & "FirstName LIKE   '" & Fname & "' AND LastName LIKE  '" & LName & "'"
            End If

            'Query for search by town
            If rgbSearchBy.SelectedIndex = 4 Then
                'write the string
                strQuery = strQuery & "TownId = " & lkTown.EditValue & " "
            End If

            'Query for search by Address
            If rgbSearchBy.SelectedIndex = 3 Then
                'If IsValidEntry() = False Then
                '    Exit Sub
                'End If
                Dim Address As String
                'Replace * by % in address textboxes
                Address = txtAddress.Text.Replace("*", "%")
                'write the string
                strQuery = strQuery & "Address1 LIKE '" & Address & "' OR Address2 LIKE '" & Address & "'"
            End If

            'Query for search by birthdate
            If rgbSearchBy.SelectedIndex = 1 Then
                'write the string
                strQuery = strQuery & " DateOfBirth BETWEEN '" & Format(CDate(dtDOBFrom.EditValue), gstrDtFormat) & "' AND '" & Format(CDate(dtDOBTo.EditValue), gstrDtFormat) & "'"
            End If

            'Query for search by LASTVISIT  
            If rgbSearchBy.SelectedIndex = 2 Then
                'write the string
                'here we need two tables ,so rewrite query from start
                strQuery = "SELECT tblPatientInfo.PatientId as [record_id],(FirstName + ' ' + LastName) as Name,DATEDIFF(yy,DateOfBirth,GETDATE()) as Age,(Address1 + ' ' + Address2) as Address ,Sex,LastName FROM tblPatientInfo   JOIN tblVisits   ON tblPatientInfo.PatientId = tblVisits.PatientId  INNER JOIN LtblSex ON tblPatientInfo.SexId=LtblSex.SexId WHERE  "

                strQuery = strQuery & "  VisitDate BETWEEN  '" & Format(CDate(dtLastVisitBetween.EditValue), gstrDtFormat & " 00:00") & "' AND '" & Format(CDate(dtLastVisitAnd.EditValue), gstrDtFormat & " 23:59") & "' "
            End If

            strQuery = strQuery & " ORDER BY LastName"

            'populate datagrid
            dsRecords = FillDataSet(strQuery)
            'Bind the grid control to the data source
            gdvRecords.Columns.Clear()

            With grdRecords
                .BeginUpdate()
                .DataSource = dsRecords.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With

            With gdvRecords
                'primary key field
                .Columns("record_id").Visible = False
                .Columns("record_id").OptionsColumn.ShowInCustomizationForm = False
                .Columns("LastName").Visible = False
                .Columns("LastName").OptionsColumn.ShowInCustomizationForm = False

                If (.Columns.Contains(.Columns.ColumnByFieldName("SelectPatient"))) Then
                    .Columns("SelectPatient").Width = 50
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Name"))) Then
                    .Columns("Name").Width = 100
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Age"))) Then
                    .Columns("Age").Width = 75
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("Address"))) Then
                    .Columns("Address").Width = 150
                End If
                If (.Columns.Contains(.Columns.ColumnByFieldName("Sex"))) Then
                    .Columns("Sex").Width = 75
                End If

                .ExpandAllGroups()
                .BestFitColumns()
            End With

            dsRecords.Dispose()
            pbRecords.Position = 80 : Application.DoEvents()

            'To set row count
            Call gdvRecords_ColumnFilterChanged(Nothing, Nothing)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
         Me.Close()
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False
        If rgbSearchBy.SelectedIndex = 0 And (Trim(txtFirstName.Text)) = "" Then
            strMsg = "Please enter first name to search for."
            txtFirstName.Focus()
        ElseIf rgbSearchBy.SelectedIndex = 0 And (Trim(txtLastName.Text)) = "" Then
            strMsg = "Please enter Last Name to search for."
            txtLastName.Focus()
        ElseIf rgbSearchBy.SelectedIndex = 3 And (Trim(txtAddress.Text)) = "" Then
            strMsg = "Please enter Address to search for."
            txtAddress.Focus()
        ElseIf rgbSearchBy.SelectedIndex = 4 And IsDBNullOrNothing(lkTown.EditValue) Then
            strMsg = "Please select Town Name to search for."
            lkTown.Focus()
        End If

        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Public Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        ShowGridPreview(grdRecords, Me.Text)
    End Sub
    Private Sub txtFirstName_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFirstName.GotFocus, txtLastName.GotFocus, txtAddress.GotFocus
        sender.SelectAll()
    End Sub

    Private Sub lkTown_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkTown.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")
        End If
    End Sub


    Private Sub txtFirstName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtFirstName.TextChanged, txtAddress.TextChanged, txtLastName.TextChanged, lkTown.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub rgbSearchBy_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rgbSearchBy.SelectedIndexChanged
        If rgbSearchBy.SelectedIndex = 0 Then
            grbNameCriteria.Visible = True
            grbDOBCriteria.Visible = False
            grbLastVisitDateCriteria.Visible = False
            grbAddressCriteria.Visible = False
            grbTown.Visible = False
            txtFirstName.Text = "*"
            txtLastName.Text = "*"
        ElseIf rgbSearchBy.SelectedIndex = 1 Then
            grbNameCriteria.Visible = False
            grbDOBCriteria.Visible = True
            grbLastVisitDateCriteria.Visible = False
            grbAddressCriteria.Visible = False
            grbTown.Visible = False
            dtDOBFrom.EditValue = Format(Today, gstrDtFormat)
            dtDOBTo.EditValue = Format(Today, gstrDtFormat)
        ElseIf rgbSearchBy.SelectedIndex = 2 Then
            grbNameCriteria.Visible = False
            grbDOBCriteria.Visible = False
            grbLastVisitDateCriteria.Visible = True
            grbAddressCriteria.Visible = False
            grbTown.Visible = False
            dtLastVisitBetween.EditValue = Format(Today, gstrDtFormat)
            dtLastVisitAnd.EditValue = Format(Today, gstrDtFormat)
        ElseIf rgbSearchBy.SelectedIndex = 3 Then
            grbNameCriteria.Visible = False
            grbDOBCriteria.Visible = False
            grbLastVisitDateCriteria.Visible = False
            grbAddressCriteria.Visible = True
            grbTown.Visible = False
            txtAddress.Text = ""
        ElseIf rgbSearchBy.SelectedIndex = 4 Then
            grbNameCriteria.Visible = False
            grbDOBCriteria.Visible = False
            grbLastVisitDateCriteria.Visible = False
            grbAddressCriteria.Visible = False
            grbTown.Visible = True
            'Fill Town combo
            Call PopulateLookupDX(lkTown, "Town", "TownId", "LtblTown", "TownId,Town", , "Town")
            lkTown.EditValue = Nothing
        End If
    End Sub

    Public Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Call PopulateData()
    End Sub

    Private Sub gdvRecords_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.Click
        Dim RowNumber As Integer = gdvRecords.FocusedRowHandle

        Dim dt As DataTable = grdRecords.DataSource

        If gdvRecords.RowCount <= 0 Then
            Exit Sub
        End If

        If SelectMultiPatients Then
            'toggle status of checkbox. and exit .this is only if we are using SelectMultiPatients
            gdvRecords.SetRowCellValue(gdvRecords.FocusedRowHandle, "CheckColumn", Not gdvRecords.GetRowCellValue(gdvRecords.FocusedRowHandle, "CheckColumn"))
            Exit Sub
        End If

        If SingleClickOnGridExit = True Then   'this  form is called by frmAppointments,so a single clickon grid 
            PatientIdForAppointment = dt.Rows(RowNumber).Item("record_id")  'will exit form and set values for patientId
            PatientNameForAppointment = dt.Rows(RowNumber).Item("Name") & "" 'and its Full Name
            Me.DialogResult = DialogResult.OK
            Me.Close()
        End If
    End Sub

    Private Sub gdvRecords_ColumnFilterChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.ColumnFilterChanged
        gdvRecords.Columns("Name").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} Record(s)")
    End Sub

    Private Sub gdvRecords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.DoubleClick
        If Not SelectMultiPatients Then
            'no row ,exit
            If gdvRecords.FocusedRowHandle < 0 Then
                Exit Sub
            End If

            'get current row number
            Dim RowNumber As Integer
            RowNumber = gdvRecords.FocusedRowHandle

            'show the patient form

            'PatientForm = New frmPatientInfo(dgdPatientSearch.Item(RowNumber, 0)) 'pass patient id as argument
            'PatientForm.Text = PatientForm.Text & " (" & dgdPatientSearch.Item(RowNumber, 1) & ")" 'set text of form as patient name
            'PatientForm.MdiParent = MainForm
            'PatientForm.Show()

            Dim frmTempPatientInfo As New frmPatientInfo(gdvRecords.GetRowCellValue(RowNumber, "record_id"))
            LoadCursor(Me)
            With frmTempPatientInfo
                .Text = .Text & " (" & gdvRecords.GetRowCellValue(RowNumber, "Name") & ")"
                .MdiParent = Me.ParentForm
                .Show()
            End With
            DestroyCrushor(Me)

            ''Refresh grid
            'btnSearch_Click(btnSearch, e)
        End If
    End Sub

    Private Sub btnAddPatient_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddPatient.Click
        Dim frmTempPatientInfo As New frmPatientInfo(-1)
        LoadCursor(Me)
        With frmTempPatientInfo
            .MdiParent = Me.ParentForm
            .Show()
            .btnAdd_Click(Nothing, Nothing)
        End With
        DestroyCrushor(Me)
    End Sub
End Class
